﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace ArticleManagementSystem
{
    public partial class _Default : Page
    {
        public void Refresh() {
            GV1.DataSource = DbHelp.dataTable("select * from Articles");
            GV1.DataBind();
        }

        public string FindData(int rowId,int columnId) {
            var a = GV1.Rows[rowId].Cells[columnId];
            var b = a.Controls.Count > 0 ? ((TextBox)a.Controls[0]).Text : a.Text;
            return b;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Refresh();
            }
        }

        protected void GV1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            GV1.EditIndex = e.RowIndex;
            var id = FindData(GV1.EditIndex, 0);
            var sql = string.Format("delete Articles where id={0} ", id);
            DbHelp.change(sql);
            GV1.EditIndex = -1;
            Refresh();
        }

        protected void GV1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GV1.EditIndex = e.NewEditIndex;
            Refresh();
        }

        protected void GV1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            GV1.EditIndex = e.RowIndex;

            var id = FindData(GV1.EditIndex, 0);
            var title = FindData(GV1.EditIndex, 1);
            var content = FindData(GV1.EditIndex, 2);
            var author = FindData(GV1.EditIndex, 3);
            var remarks = FindData(GV1.EditIndex, 4);
            var a = int.TryParse(id, out int b);
            if (a)
            {
                var sql = string.Format("update Articles set Title='{0}',Content='{1}',Author='{2}',Remarks='{3}' where id={4}",title,content,author,remarks,id);
                DbHelp.change(sql);
            }
            else
            {
                var sql = string.Format("insert into  Articles(Title,Content,Author,Remarks) values('{0}','{1}','{2}','{3}')", title,content,author,remarks);
                DbHelp.change(sql);
            }
            GV1.EditIndex = -1;
            Refresh();
        }

        protected void GV1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GV1.EditIndex = -1;
            Refresh();
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            var dt = DbHelp.dataTable("select * from Articles");
            var table = dt.Copy();
            table.Rows.Add(table.NewRow());
            GV1.DataSource = table;
            GV1.EditIndex = table.Rows.Count - 1;
            GV1.DataBind();

        }
    }
}